import 'package:flutter/material.dart';
import 'package:dio/dio.dart';

import '../services/screen_adapter.dart';
import '../model/product_model.dart';
import '../config/config.dart';
import '../widget/loading_widget.dart';

class ProductListPage extends StatefulWidget {

  final Map arguments;

  ProductListPage({Key key, this.arguments}) : super(key: key);

  @override
  _ProductListPageState createState() => _ProductListPageState();
}

class _ProductListPageState extends State<ProductListPage> {

  // Scaffold key
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
  // 用于上拉分页
  ScrollController  _scrollController = ScrollController();
  // 分页
  int _page = 1;
  // 每页有多少条数据
  int _pageSize = 8;
  // 数据
  List _productList = [];
  // 排序： 价格升序sort=price_1, 价格降序sort=price_-1，销量升序sort=salecount_1, 销量降序sort=salecount_-1
  String _sort = "";
  // 解决上拉分页重复请求的问题
  bool _flag = true;
  // 是否有数据
  bool _hasMore = true;
  // 是否有搜索数据
  bool _hasData = true;
  // 二级导航数据
  List _subHeaderList = [
    {'id' : 1, 'title' : '综合', 'fields': 'all', 'sort': -1 },
    {'id' : 2, 'title' : '销量', 'fields': 'salecount', 'sort': -1 },
    {'id' : 3, 'title' : '价格', 'fields': 'price', 'sort': -1 },
    {'id' : 4, 'title' : '筛选' }
  ];
  // 默认选中二级导航的菜单
  int _selectHeaderId = 1;
  // 配置search搜索框的值
  var _initKeywordsController = TextEditingController(); 
  // cid
  var _cid;
  // keywords
  var _keywords;

  @override
  void initState() {
    super.initState();

    this._cid = widget.arguments['cid'];
    this._keywords = widget.arguments['keywords'];

    // 给search框赋值
    this._initKeywordsController.text = this._keywords;

    _getProductListData();
    
    // 监听滚动条滚动事件
    _scrollController.addListener(() {
      var pixel = _scrollController.position.pixels; //获取滚动条滚动的高度
      var maxScrollExtent = _scrollController.position.maxScrollExtent; //获取页面高度
      if (pixel > maxScrollExtent - 20) { //距离底部还有20的时候下拉分页加载更多
        if (_flag && _hasMore) {
          _getProductListData();
        }
      }
     });
  }

  // 获取商品列表数据
  _getProductListData() async{
    setState(() => this._flag = false);

    var api;
    if(this._keywords == null) {
      api = "${Config.domain}api/plist?cid=${this._cid}&page=$_page&sort=$_sort&pageSize=$_pageSize";
    } else {
      // api = "${Config.domain}api/plist?search=${widget.arguments['keywords']}&page=$_page&sort=$_sort&pageSize=$_pageSize";
      api = "${Config.domain}api/plist?search=${this._keywords}&page=$_page&sort=$_sort&pageSize=$_pageSize";
    }

    // print(api);
    var result = await Dio().get(api);
    var productList = ProductModel.fromJson(result.data);
    
    // 判断是否有搜索内容
    if(productList.result.length == 0 && this._page == 1) {
      setState(() => this._hasData = false);
    } else {
      setState(() => this._hasData = true);
    }

    // 判断最后一页有没有数据
    if(productList.result.length < this._pageSize) {
      setState(() {
        this._productList.addAll(productList.result);
        this._flag = true;
        this._hasMore = false;
      });
    } else{
      setState(() {
        this._productList.addAll(productList.result);
        this._page++;
        this._flag = true;
      });
    }

  }

  // 显示加载中
  Widget _showMore(index) {
    if(this._hasMore) {
      return (index == this._productList.length-1) ? LoadingWidget() : Text('');
    } else {
      return (index == this._productList.length-1) ? Text('---------- 我是有底线的 ----------') : Text('');
    }
  }

  // 商品列表
  Widget _productListWidget() {
    if(this._productList.length > 0) {
      return Container(
        padding: EdgeInsets.all(10),
        margin: EdgeInsets.only(top: ScreenAdapter.height(80)),
        child: ListView.builder(
          controller: _scrollController, //上拉刷新数据控制
          itemCount: this._productList.length,
          itemBuilder: (context, index) { 
            // 处理图片地址
            String pic = this._productList[index].pic;
            pic = Config.domain + pic.replaceAll('\\', '/');
            // 每一个元素
            return Column(
              children: <Widget>[
                Row(
                  children: <Widget>[
                    // 左侧
                    Container(
                      width: ScreenAdapter.width(180),
                      height: ScreenAdapter.height(180),
                      child: Image.network('$pic', fit: BoxFit.cover)
                    ),
                    // 右侧
                    Expanded(
                      flex: 1,
                      child: Container(
                        height: ScreenAdapter.height(180),
                        margin: EdgeInsets.only(left: 10),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween, //垂直
                          crossAxisAlignment: CrossAxisAlignment.start, //水平
                          children: <Widget>[
                            Text(
                              '${this._productList[index].title}',
                              maxLines: 2,
                              overflow: TextOverflow.ellipsis
                            ),
                            Row(
                              children: <Widget>[
                                Container(
                                  height: ScreenAdapter.height(36),
                                  margin: EdgeInsets.only(right: 10),
                                  padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(10),
                                    color: Color.fromRGBO(230, 230, 230, 0.9)
                                  ), 
                                  child: Text('4g')
                                ),
                                Container(
                                  height: ScreenAdapter.height(36),
                                  margin: EdgeInsets.only(right: 10),
                                  padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                                  //注意：Container用了decoration属性，这时color属性必须放在BoxDecoration里面
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(10),
                                    color: Color.fromRGBO(230, 230, 230, 0.9)
                                  ), 
                                  child: Text('126')
                                )
                              ], 
                            ),
                            Text(
                              '¥${this._productList[index].price}',
                              style: TextStyle(
                                color: Colors.red,
                                fontSize: 16
                              )
                            )
                          ],
                        )
                      )
                    )
                  ],
                ),
                Divider(height: 20),
                // 每次渲染的时候，在最后一条后加个加载组件
                _showMore(index)
              ],
            );
          }
        ),
      );
    } else {
      // 加载中
      return LoadingWidget();
    }

    
  }

  // 导航改变的时候触发
  _subHeaderChange(id) {
    if(id == 4) {
      setState(() {
        this._selectHeaderId = id;
      });
      // 打开侧边栏
      _scaffoldKey.currentState.openEndDrawer();
    } else {
      setState(() {
        this._selectHeaderId = id;
        this._sort = '${this._subHeaderList[id-1]['fields']}_${this._subHeaderList[id-1]['sort']}';
        // 重置分页
        this._page = 1;
        // 重置数据
        this._productList = [];
        // 再次点击菜单切换升降序
        this._subHeaderList[id-1]['sort'] = this._subHeaderList[id-1]['sort'] * -1;
        // 回到顶部
        this._scrollController.jumpTo(0);
        // 重置_hasMore
        this._hasMore = true;
        // 重新请求数据
        this._getProductListData();
      });
    }
    
  }

  // 显示Header Icon
  Widget _showIcon(id) {
    if(id == 2 || id == 3) {
      if(this._subHeaderList[id-1]['sort'] == 1) {
        return Icon(Icons.arrow_drop_down);
      } else {
        return Icon(Icons.arrow_drop_up);
      }
      
    } else {
      return Text('');
    } 
  }

  // 筛选导航
  Widget _subHeaderWidget() {
    return Positioned(
      top: 0,
      width: ScreenAdapter.width(750),
      height: ScreenAdapter.height(80),
      child: Container(
        width: ScreenAdapter.width(750),
        height: ScreenAdapter.height(80),
        decoration: BoxDecoration(
          border: Border(
            bottom: BorderSide(
              width: 1,
              color: Color.fromRGBO(233, 233, 233, 0.9)
            )
          ) 
        ),
        child: Row(
          children: this._subHeaderList.map((e) { 
            return Expanded(
              flex: 1,
              child: InkWell(
                onTap: () {
                  _subHeaderChange(e['id']);
                },
                child: Padding(
                  padding: EdgeInsets.fromLTRB(0, ScreenAdapter.height(16), 0, ScreenAdapter.height(16)),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Text(
                        "${e['title']}",
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          color: this._selectHeaderId == e['id'] ? Colors.red : Colors.black54
                        )
                      ),
                      _showIcon(e['id'])
                    ]
                  )
                )
              )
            );
          }).toList()
            
        ) 
      )
    );
  }

  @override
  Widget build(BuildContext context) {

    ScreenAdapter.init();

    return Container(
       child: Scaffold(
          key: _scaffoldKey,
          appBar: AppBar(
            title: Container(
              height: ScreenAdapter.height(68), 
              decoration: BoxDecoration(
                  color: Color.fromRGBO(233, 233, 233, 0.8),
                  borderRadius: BorderRadius.circular(30)
                ),
              child: TextField(
                controller: this._initKeywordsController,
                autofocus: false,
                decoration: InputDecoration(
                  border: OutlineInputBorder(
                    borderSide: BorderSide.none, //去掉四周的边框
                    borderRadius: BorderRadius.circular(30)
                  )
                ),
                onChanged: (value) {
                  setState(() => this._keywords = value);
                }
              )
            ),
            actions: <Widget>[
              InkWell(
                onTap: () {
                  this._subHeaderChange(1);
                }, 
                child: Container(
                  height: ScreenAdapter.height(68), 
                  width: ScreenAdapter.height(80),
                  child: Row(
                    // mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Text('搜索')
                    ],
                  )
                )
              )
            ],
          ), 
          endDrawer: Drawer(
            child: Container(
              child: Text('实现筛选功能') 
            )
          ),
          body: _hasData ? Stack(
            children: <Widget>[
              _productListWidget(),
              _subHeaderWidget() 
            ],
          ) : Center(
            child: Text('没有您要浏览的数据') 
          )
       )
    );
  }
}